package com.demo.servlet.demo1216.service.impl;

import com.demo.servlet.demo1216.dao.AccountDao;
import com.demo.servlet.demo1216.dao.impl.AccountDaoImpl;
import com.demo.servlet.demo1216.entity.Account;
import com.demo.servlet.demo1216.service.AccountService;
import com.demo.servlet.demo1216.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.SQLException;

public class AccountServiceImpl implements AccountService {
    AccountDao accountDao = new AccountDaoImpl();

    @Override
    public void transfer(Account from, Account to, double money) {
        Connection connection = JdbcUtils.getConnection();
        try {
            //开启事务、设置自动提交为 false
            connection.setAutoCommit(false);
            //把转账人的金额 - money
            from.setMoney(from.getMoney() - money);
            //把收款人的金额 + money
            to.setMoney(to.getMoney() + money);
            //分别进行更新
            accountDao.update(from);
            int i = 1 / 0;
            accountDao.update(to);
            //提交事务
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                //遇到异常 回滚事务
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public Account queryByName(String name) {
        return accountDao.queryByName(name);
    }
}
